<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试记录管理</span>
          <div>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出记录
            </el-button>
            <el-button type="info" @click="handleStatistics">
              <el-icon><DataAnalysis /></el-icon>
              统计分析
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="考试名称" prop="examTitle">
            <el-input
              v-model="queryParams.examTitle"
              placeholder="请输入考试名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentName">
            <el-input
              v-model="queryParams.studentName"
              placeholder="请输入学生姓名"
              clearable
              style="width: 150px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="考试状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="进行中" value="IN_PROGRESS" />
              <el-option label="已提交" value="SUBMITTED" />
              <el-option label="已评分" value="GRADED" />
              <el-option label="超时" value="TIMEOUT" />
              <el-option label="作弊" value="CHEATING" />
            </el-select>
          </el-form-item>
          <el-form-item label="考试类型" prop="examType">
            <el-select v-model="queryParams.examType" placeholder="请选择类型" clearable style="width: 120px">
              <el-option label="期中考试" value="MIDTERM" />
              <el-option label="期末考试" value="FINAL" />
              <el-option label="随堂测验" value="QUIZ" />
              <el-option label="作业" value="HOMEWORK" />
            </el-select>
          </el-form-item>
          <el-form-item label="考试时间">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="记录ID" align="center" prop="id" width="80" />
        <el-table-column label="考试名称" align="left" prop="examTitle" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="学生信息" align="center" width="150">
          <template #default="scope">
            <div>
              <div>{{ scope.row.studentName }}</div>
              <div class="text-muted">{{ scope.row.studentNumber }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="考试类型" align="center" prop="examType" width="100">
          <template #default="scope">
            <el-tag :type="getExamTypeTagType(scope.row.examType)">
              {{ getExamTypeText(scope.row.examType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="得分情况" align="center" width="120">
          <template #default="scope">
            <div>
              <div class="score-text" :class="getScoreClass(scope.row.score, scope.row.totalScore)">
                {{ scope.row.score || 0 }} / {{ scope.row.totalScore }}
              </div>
              <div class="text-muted">{{ getScorePercentage(scope.row.score, scope.row.totalScore) }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用时" align="center" prop="duration" width="100">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="submitTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.submitTime ? parseTime(scope.row.submitTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" icon="View" @click="handleDetail(scope.row)" link>查看详情</el-button>
            <el-button
              v-if="scope.row.status === 'SUBMITTED'"
              type="success"
              icon="Edit"
              @click="handleGrade(scope.row)"
              link
            >
              评分
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" style="margin-left: 10px">
              <el-button type="primary" link>
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleAnswers" icon="Document">答题详情</el-dropdown-item>
                  <el-dropdown-item command="handleReview" icon="View">试卷回顾</el-dropdown-item>
                  <el-dropdown-item command="handleCheatLog" icon="Warning" v-if="scope.row.hasCheatLog">作弊记录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 考试记录详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="900px" append-to-body>
      <div v-if="recordDetail" class="record-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h4>基本信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="考试名称">{{ recordDetail.examTitle }}</el-descriptions-item>
            <el-descriptions-item label="学生姓名">{{ recordDetail.studentName }}</el-descriptions-item>
            <el-descriptions-item label="学号">{{ recordDetail.studentNumber }}</el-descriptions-item>
            <el-descriptions-item label="考试类型">{{ getExamTypeText(recordDetail.examType) }}</el-descriptions-item>
            <el-descriptions-item label="总分">{{ recordDetail.totalScore }}</el-descriptions-item>
            <el-descriptions-item label="得分">{{ recordDetail.score || '未评分' }}</el-descriptions-item>
            <el-descriptions-item label="用时">{{ formatDuration(recordDetail.duration) }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ getStatusText(recordDetail.status) }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ parseTime(recordDetail.startTime) }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{ recordDetail.submitTime ? parseTime(recordDetail.submitTime) : '未提交' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 答题统计 -->
        <div class="detail-section">
          <h4>答题统计</h4>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ recordDetail.totalQuestions }}</div>
                <div class="stat-label">总题数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value correct">{{ recordDetail.correctCount || 0 }}</div>
                <div class="stat-label">正确</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value wrong">{{ recordDetail.wrongCount || 0 }}</div>
                <div class="stat-label">错误</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value unanswered">{{ recordDetail.unansweredCount || 0 }}</div>
                <div class="stat-label">未答</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 作弊检测记录 -->
        <div v-if="recordDetail.cheatLogs && recordDetail.cheatLogs.length > 0" class="detail-section">
          <h4>作弊检测记录</h4>
          <el-table :data="recordDetail.cheatLogs" style="width: 100%">
            <el-table-column prop="type" label="类型" width="120">
              <template #default="scope">
                <el-tag type="danger">{{ getCheatTypeText(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="time" label="时间" width="160">
              <template #default="scope">
                {{ parseTime(scope.row.time) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog title="手动评分" v-model="gradeOpen" width="600px" append-to-body>
      <el-form ref="gradeRef" :model="gradeForm" :rules="gradeRules" label-width="100px">
        <el-form-item label="学生姓名">
          <span>{{ gradeForm.studentName }}</span>
        </el-form-item>
        <el-form-item label="考试名称">
          <span>{{ gradeForm.examTitle }}</span>
        </el-form-item>
        <el-form-item label="总分">
          <span>{{ gradeForm.totalScore }}</span>
        </el-form-item>
        <el-form-item label="得分" prop="score">
          <el-input-number
            v-model="gradeForm.score"
            :min="0"
            :max="gradeForm.totalScore"
            controls-position="right"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="评语">
          <el-input
            v-model="gradeForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入评语（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="gradeOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitGrade">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ExamRecord">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, DataAnalysis, Search, Refresh, View, Edit, Document, Warning } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const detailOpen = ref(false)
const gradeOpen = ref(false)
const detailTitle = ref('')
const queryRef = ref()
const gradeRef = ref()
const dateRange = ref([])

// 列表数据
const recordList = ref([])
const recordDetail = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  examTitle: undefined,
  studentName: undefined,
  status: undefined,
  examType: undefined,
  startTime: undefined,
  endTime: undefined
})

// 评分表单
const gradeForm = reactive({
  id: undefined,
  studentName: '',
  examTitle: '',
  totalScore: 0,
  score: 0,
  comment: ''
})

// 评分表单验证规则
const gradeRules = reactive({
  score: [
    { required: true, message: '请输入得分', trigger: 'blur' },
    { type: 'number', min: 0, message: '得分不能小于0', trigger: 'blur' }
  ]
})

// 获取考试记录列表
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    // 模拟API调用
    const mockData = {
      code: 200,
      data: {
        total: 50,
        rows: [
          {
            id: 1,
            examId: 1,
            examTitle: 'JavaScript基础知识测试',
            examType: 'QUIZ',
            studentId: 1,
            studentName: '张三',
            studentNumber: '2024001',
            totalScore: 100,
            score: 85,
            duration: 45,
            status: 'GRADED',
            startTime: '2024-01-15 09:00:00',
            submitTime: '2024-01-15 09:45:00',
            hasCheatLog: false,
            totalQuestions: 20,
            correctCount: 17,
            wrongCount: 3,
            unansweredCount: 0
          },
          {
            id: 2,
            examId: 2,
            examTitle: 'Vue.js框架期中考试',
            examType: 'MIDTERM',
            studentId: 2,
            studentName: '李四',
            studentNumber: '2024002',
            totalScore: 120,
            score: null,
            duration: 90,
            status: 'SUBMITTED',
            startTime: '2024-01-15 14:00:00',
            submitTime: '2024-01-15 15:30:00',
            hasCheatLog: false,
            totalQuestions: 30,
            correctCount: null,
            wrongCount: null,
            unansweredCount: null
          },
          {
            id: 3,
            examId: 1,
            examTitle: 'JavaScript基础知识测试',
            examType: 'QUIZ',
            studentId: 3,
            studentName: '王五',
            studentNumber: '2024003',
            totalScore: 100,
            score: 0,
            duration: 120,
            status: 'TIMEOUT',
            startTime: '2024-01-15 10:00:00',
            submitTime: null,
            hasCheatLog: true,
            totalQuestions: 20,
            correctCount: 0,
            wrongCount: 0,
            unansweredCount: 20,
            cheatLogs: [
              {
                type: 'TAB_SWITCH',
                description: '检测到切换浏览器标签页',
                time: '2024-01-15 10:15:00'
              },
              {
                type: 'COPY_PASTE',
                description: '检测到复制粘贴操作',
                time: '2024-01-15 10:20:00'
              }
            ]
          },
          {
            id: 4,
            examId: 3,
            examTitle: 'React开发实战',
            examType: 'FINAL',
            studentId: 4,
            studentName: '赵六',
            studentNumber: '2024004',
            totalScore: 150,
            score: 128,
            duration: 105,
            status: 'GRADED',
            startTime: '2024-01-16 09:00:00',
            submitTime: '2024-01-16 10:45:00',
            hasCheatLog: false,
            totalQuestions: 25,
            correctCount: 22,
            wrongCount: 3,
            unansweredCount: 0
          },
          {
            id: 5,
            examId: 4,
            examTitle: 'HTML/CSS基础',
            examType: 'HOMEWORK',
            studentId: 5,
            studentName: '孙七',
            studentNumber: '2024005',
            totalScore: 80,
            score: 72,
            duration: 60,
            status: 'GRADED',
            startTime: '2024-01-16 15:00:00',
            submitTime: '2024-01-16 16:00:00',
            hasCheatLog: false,
            totalQuestions: 16,
            correctCount: 14,
            wrongCount: 2,
            unansweredCount: 0
          }
        ]
      }
    }

    recordList.value = mockData.data.rows
    total.value = mockData.data.total
  } catch (error) {
    console.error('获取考试记录失败:', error)
    ElMessage.error('获取考试记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  dateRange.value = []
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 查看详情操作
const handleDetail = (row) => {
  recordDetail.value = { ...row }
  detailTitle.value = `考试记录详情 - ${row.studentName}`
  detailOpen.value = true
}

// 评分操作
const handleGrade = (row) => {
  Object.assign(gradeForm, {
    id: row.id,
    studentName: row.studentName,
    examTitle: row.examTitle,
    totalScore: row.totalScore,
    score: row.score || 0,
    comment: ''
  })
  gradeOpen.value = true
}

// 提交评分
const submitGrade = () => {
  gradeRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 模拟评分API调用
        ElMessage.success('评分成功')
        gradeOpen.value = false
        getList()
      } catch (error) {
        ElMessage.error('评分失败')
      }
    }
  })
}

// 导出记录
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 统计分析
const handleStatistics = () => {
  ElMessage.info('统计分析功能开发中')
}

// 下拉菜单操作
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleAnswers':
      ElMessage.info('查看答题详情功能开发中')
      break
    case 'handleReview':
      ElMessage.info('试卷回顾功能开发中')
      break
    case 'handleCheatLog':
      handleDetail(row)
      break
  }
}

// 工具函数
const getExamTypeText = (type) => {
  const typeMap = {
    'MIDTERM': '期中考试',
    'FINAL': '期末考试',
    'QUIZ': '随堂测验',
    'HOMEWORK': '作业',
    'MOCK': '模拟考试'
  }
  return typeMap[type] || '未知'
}

const getExamTypeTagType = (type) => {
  const typeMap = {
    'MIDTERM': 'warning',
    'FINAL': 'danger',
    'QUIZ': 'primary',
    'HOMEWORK': 'success',
    'MOCK': 'info'
  }
  return typeMap[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'IN_PROGRESS': '进行中',
    'SUBMITTED': '已提交',
    'GRADED': '已评分',
    'TIMEOUT': '超时',
    'CHEATING': '作弊'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    'IN_PROGRESS': 'warning',
    'SUBMITTED': 'primary',
    'GRADED': 'success',
    'TIMEOUT': 'danger',
    'CHEATING': 'danger'
  }
  return typeMap[status] || 'info'
}

const getCheatTypeText = (type) => {
  const typeMap = {
    'TAB_SWITCH': '切换标签页',
    'COPY_PASTE': '复制粘贴',
    'FULL_SCREEN_EXIT': '退出全屏',
    'MOUSE_LEAVE': '鼠标离开',
    'KEYBOARD_SHORTCUT': '快捷键操作'
  }
  return typeMap[type] || '未知'
}

const getScoreClass = (score, totalScore) => {
  if (!score) return ''
  const percentage = (score / totalScore) * 100
  if (percentage >= 90) return 'excellent'
  if (percentage >= 80) return 'good'
  if (percentage >= 60) return 'pass'
  return 'fail'
}

const getScorePercentage = (score, totalScore) => {
  if (!score || !totalScore) return 0
  return Math.round((score / totalScore) * 100)
}

const formatDuration = (minutes) => {
  if (!minutes) return '0分钟'
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`
}

const parseTime = (time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.score-text {
  font-weight: bold;

  &.excellent {
    color: #67c23a;
  }

  &.good {
    color: #409eff;
  }

  &.pass {
    color: #e6a23c;
  }

  &.fail {
    color: #f56c6c;
  }
}

.record-detail {
  .detail-section {
    margin-bottom: 24px;

    h4 {
      margin-bottom: 16px;
      color: #303133;
      border-bottom: 2px solid #409eff;
      padding-bottom: 8px;
    }
  }

  .stat-item {
    text-align: center;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 8px;

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 4px;

      &.correct {
        color: #67c23a;
      }

      &.wrong {
        color: #f56c6c;
      }

      &.unanswered {
        color: #909399;
      }
    }

    .stat-label {
      color: #606266;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 分页组件样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: right;
}
</style>
